package org.aeon.client.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.client.context.GlobalContext;
import org.aeon.client.view.components.menuPanel.PopupPrompt;
import org.aeon.client.view.components.sessionPanel.ChatRecordPanel;
import org.aeon.client.view.components.sessionPanel.UserChatPanel;
import org.aeon.constant.MessageSendStatus;
import org.aeon.entity.ChatMessage;
import org.aeon.entity.User;
import org.aeon.entity.dto.UserInfoDto;
import org.aeon.message.request.UserInfoRequestMessage;
import org.aeon.message.response.ChatResponseMessage;
import org.aeon.service.UserMessageService;
import org.aeon.utils.SimpleRequestUtil;

import javax.swing.*;
import java.util.Date;

import static org.aeon.client.context.MessageMap.MessageContextKey.UserInfo;

/**
 * @author: MissingAeon
 * @date: 2024/1/26 12:38
 * @description: 聊天响应消息处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class ChatResponseHandler extends SimpleChannelInboundHandler<ChatResponseMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatResponseMessage msg) throws Exception {
        final GlobalContext context = GlobalContext.getContext();
        final User user = context.getCurrentUser();
        final ChatMessage message = msg.getChatMessage();
        if (msg.isSuccess()) {
            // 不是自己发的消息
            if (user.getId() != message.getFrom()) {
                try {
                    // 显示新消息
                    SwingUtilities.invokeLater(() -> {
                        final UserChatPanel panel = context.getSessionPanel().getPanel(UserChatPanel.class);
                        if (panel != null) {
                            final ChatRecordPanel recordPanel = panel.getRecordPanel();
                            recordPanel.newNews(msg.getChatMessage(), MessageSendStatus.NORMAL);
                            recordPanel.setScrollBar(-1);
                        }
                    });

                    // 获取发送者信息
                    final UserInfoRequestMessage reqMsg = new UserInfoRequestMessage();
                    reqMsg.setMessage(msg.getChatMessage().getFrom());
                    SimpleRequestUtil.sendAndWait(context, reqMsg, () -> {
                        final UserInfoDto userInfoDto = context.getMessageMap().del(UserInfo);
                        GlobalContext.getContext().getListColumnPanel().
                                getMessageListPanel().addItem(userInfoDto, new Date(message.getCreationTime()));
                    });

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
                // 保存
                UserMessageService.service.writeMessages(msg.getChatMessage(), user.getId());
            } else {
                context.getUserChatMap().put(msg.getResponseID(), message);
            }
            ctx.fireChannelRead(msg);
        }
        PopupPrompt.createPopUp(msg.getReason());
    }
}
